<template>
	<view class="login-box" v-if="showLogin">
		<view class="fork" @click="goFork">
			<image src="../../static/images/close.png" mode=""></image>
		</view>
		<!-- 只有在小程序的情况下才显示 -->
		<!-- #ifdef MP-WEIXIN -->
		<view class="studyCenter" v-if="getUserInfoTag">
			<h4>前端交流学习中心欢迎你</h4>
			<button class="btn" type="primary" open-type='getUserInfo' @click="getInfoMes">
				<image class="wx" src="../../static/images/wechat.png" mode=""></image>
				<text>一键获取微信信息</text>
			</button>
		</view>
		<!-- #endif -->

		<view class="formArea" v-show="!getUserInfoTag">
			<u-form :model="form" ref="form">
				<u-form-item label="账号" required label-width="140" prop="login"
					v-show="logOrResType === 'passwordLogin'">
					<u-input v-model="form.login" required placeholder="输入手机号/邮箱/昵称" />
				</u-form-item>
				<u-form-item label="昵称" required label-width="140" prop="name"
					v-show="logOrResType === 'phoneRegister' || logOrResType === 'emailRegister'">
					<u-input v-model="form.name" placeholder="2-10个字符" />
				</u-form-item>
				<u-form-item label="电话" required label-width="140" prop="phone"
					v-show="logOrResType === 'codeLogin' || logOrResType === 'phoneRegister'">
					<u-input v-model="form.phone" placeholder="输入11位手机号码" />
				</u-form-item>
				<u-form-item label="邮箱" required label-width="140" prop="email"
					v-show="logOrResType === 'emailRegister'">
					<u-input v-model="form.email" type="email" placeholder="输入邮箱" />
				</u-form-item>
				<u-form-item label="验证码" required label-width="140" prop="verifiable_code"
					v-show="logOrResType !== 'passwordLogin'">
					<u-input v-model="form.verifiable_code" placeholder="请输入4位验证码" />
					<u-button slot="right" @click="getCode(logOrResType)" size="mini" type="primary">获取验证码</u-button>
				</u-form-item>
				<u-form-item label="密码" required label-width="140" prop="password" v-show="logOrResType !=='codeLogin'">
					<u-input v-model="form.password" type="password" placeholder="限4-20个字符,区分大小写" />
				</u-form-item>
				<u-form-item label="重复密码" required label-width="140" prop="repassword"
					v-show="logOrResType === 'phoneRegister' || logOrResType === 'emailRegister'">
					<u-input v-model="form.repassword" type="password" placeholder="限4-20个字符,区分大小写" />
				</u-form-item>
			</u-form>
			<view class="btns">
				<u-button @click="submit" class='submit'>提交</u-button>
				<u-button @click="onCancel">取消</u-button>
			</view>
			<view class="login-register">
				<text :class="logOrResType === 'passwordLogin' ? 'textActive' : ''" @click="changeType(0)">密码登录</text>
				<text :class="logOrResType === 'codeLogin' ? 'textActive' : ''" @click="changeType(1)">验证码登录</text>
				<text :class="logOrResType === 'phoneRegister' ? 'textActive' : ''" @click="changeType(2)">手机注册</text>
				<text :class="logOrResType === 'emailRegister' ? 'textActive' : ''" @click="changeType(3)">邮箱注册</text>
			</view>
		</view>

		<view class="btnInfo">
			<view>点击登录/注册前端论坛,即表示已阅读并同意</view>
			<view class="webInfo">
				<view @tap="gotoWeb('https://uniapp.dcloud.io/component/mp-weixin-plugin')">《隐私政策》</view>
				<view @tap="gotoWeb('https://developers.weixin.qq.com/miniprogram/dev/framework/')">《用户协议》</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapActions } from 'vuex'
	export default {
		name: "login",
		data() {
			return {
				showLogin: true,
				// 是否获取用户信息
				// #ifndef MP-WEIXIN
				getUserInfoTag: false,
				// #endif
				// #ifdef MP-WEIXIN
				getUserInfoTag: true,
				// #endif
				// 表单数据
				form: {
					login: '',
					name: '',
					phone: '',
					email: '',
					verifiable_code: '',
					password: '',
					repassword: '',
					avatar: ''
				},
				// 登录与注册状态
				logOrResType: 'passwordLogin',

				rules: {
					login: [{
						validator: (rule, value, callback) => {
							if (this.logOrResType === 'passwordLogin') {
								return !this.$u.test.isEmpty(value)
							} else {
								return true
							}
						},
						required: true,
						trigger: 'blur',
						message: '请输入手机号/邮箱/昵称'
					}],
					name: [{
						asyncValidator: async (rule, value, callback) => {
							// 只有在 电话、邮箱注册的时候才会触发该校验规则
							if (this.logOrResType === 'phoneRegister' || this.logOrResType === 'emailRegister') {
								let {data} = await this.$u.api.getUsers({
									name: value
								})
								let val = data.find(item=>item.name === value)
								if (val && val.name === value) {
									callback(new Error('当前用户昵称已存在,请重新输入'))
								} else {
									callback()
								}
							} else {
								callback()
							}
						},
					}, {
						validator: (rule, value, callback) => {
							if (this.logOrResType === 'phoneRegister' || this.logOrResType ===
								'emailRegister') {
								return this.$u.test.rangeLength(value, [2, 10])
							} else {
								return true
							}
						},
						message: '必填* 昵称长度请在2-10位之间',
						trigger: ['change', 'blur'],
						required: true,
					}],
					phone: [{
						validator: (rule, value, callback) => {
							// 手机号码格式判断
							if (this.logOrResType === 'codeLogin' || this.logOrResType === 'phoneRegister') {
									// 上面有说，返回true表示校验通过，返回false表示不通过
									// this.$u.test.mobile()就是返回true或者false的
							    return this.$u.test.mobile(value)
							} else {
								return true
							}
						},
						required: true,
						message: '必填 * 手机号码输入不正确',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur']
					}],
					email: [{
						validator: (rule, value, callback) => {
							// 手机号码格式判断
							if (this.logOrResType === 'emailRegister') {
								// 自带判断 电话号码合法性方法
								return this.$u.test.email(value)
							} else {
								return true
							}
						},
						message: '必填 * 邮箱输入不正确',
						trigger: ['change', 'blur'],
						required: true
					}],
					verifiable_code: [{
						validator: (rule, value, callback) => {
							if (this.logOrResType !== 'passwordLogin') {
								return value === '8888'
							} else {
								return true
							}
						},
						message: '必填 * 验证码输入错误',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur'],
						required: true
					}],
					password: [{
						validator: (rule, value, callback) => {
							if (this.logOrResType !== 'codeLogin') {
								return value.length >= 4 && value.length <= 20
							} else {
								return true
							}
						},
						message: '必填* 密码长度要求在4-20位之间',
						trigger: ['change', 'blur'],
						required: true
					}],
					repassword: [{
						validator: (rule, value, callback) => {
							if (this.logOrResType === 'phoneRegister' || this.logOrResType === 'emailRegister') {
								return this.form.password === value
							} else {
								return true
							}
						},
						message: '必填 * 两次密码输入不一致',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur'],
						required: true
					}]
				},
			};
		},
		created() {
			// 获取当前用户设置
			// #ifdef MP-WEIXIN
			wx.getSetting({
				success: (res => {
					if (res.authSetting['scope.userInfo']) {
						uni.getUserInfo({
							success: res => {
								this.getUserInfoTag = false
								this.form.login = res.userInfo.nickName
								this.form.name = res.userInfo.nickName
								this.form.avatar = res.userInfo.avatarUrl
							},
							fail: () => {
								console.log('用户未授权！')
							}
						})
					}
				})
			})
			// #endif
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			...mapActions(['userLoginActions']),
			// 表单提交
			submit() {
				this.$refs.form.validate(async valid => {
					if (!valid) {
						uni.showToast({
							title: '请检查输入',
							icon: 'loading'
						})
						return false
					}
					switch (this.logOrResType) {
						case 'passwordLogin':
							let res = await this.$u.api.userLogin({
								login: this.form.login,
								password: this.form.password
							})
							if (res.statusCode === 200 && res.data.access_token) {
								uni.showToast({
									title:'登录成功',
									icon:'success'
								})
								this.getUsersSuccessInfo(res.data.access_token)
							} else {
								uni.showToast({
									title:'账号/密码错误,请重新输入',
									icon:'none'
								})
							}
							break;
						case 'codeLogin':
							if (valid) {
								let res1 = await this.$u.api.userLogin({
									login: this.form.phone,
									verifiable_code: '8888'
								})
								if (res1.statusCode === 200 && res1.data && res1.data.access_token) {
									uni.showToast({
										title:'登录成功',
										icon:'success'
									})
									this.getUsersSuccessInfo(res1.data.access_token)
								} else {
									uni.showToast({
										title:'电话/验证码输入有误,请重新输入',
										icon: 'none'
									})
								}
							}
							break;
						case 'phoneRegister':
							let rdata = await this.$u.api.userRegister({
								name: this.form.name,
								phone: this.form.phone,
								verifiable_code: '8888',
								password: this.form.password,
								verifiable_type: 'sms'
							})
							if (rdata.statusCode === 200) {
								uni.showToast({
									title:'注册成功',
									icon:'success'
								})
							} else {
								uni.showToast({
									title:'注册失败'
								})
							}
							break;
						case 'emailRegister':
							let rdata1 = await this.$u.api.userRegister({
								name: this.form.name,
								email: this.form.email,
								verifiable_code: '8888',
								password: this.form.password,
								verifiable_type: 'mail'
							})
							if (rdata1.statusCode === 200) {
								uni.showToast({
									title:'注册成功',
									icon:'success'
								})
							} else {
								uni.showToast({
									title:'注册失败'
								})
							}
							break;
					}
				});
			},
			
			// 打开login组件
			openLogin () {
				this.showLogin = true
			},
			// 点击叉号,关闭login组件
			goFork () {
				this.showLogin = false
			},
			gotoWeb(url) {
				wx.navigateTo({
					url: '/pages/web-view/web-view?link=' + encodeURI(url)
				});
			},
			// 获取当前用户信息
			getInfoMes() {
				uni.getUserInfo({
					success: res => {
						this.getUserInfoTag = false
						this.form.login = res.userInfo.nickName
						this.form.name = res.userInfo.nickName
						this.form.avatar = res.userInfo.avatarUrl
					},
					fail: () => {
						console.log('用户未授权！')
					}
				})
			},
			// 获取当前验证码
			async getCode(logOrResType) {
				// // 已经注册成功的手机后,获取验证码登录
				if (logOrResType === 'codeLogin') {
					let res = await this.$u.api.getLoginCode({
						phone: this.form.phone
					})
					if(res.statusCode ===200){
						uni.showModal({
							title: '获取验证码成功',
							content: '8888'
						})
					}
				}
				if (logOrResType === 'phoneRegister') {
					let res = await this.$u.api.getRegisterCode({
						phone: this.form.phone
					})
					if(res.statusCode ===200){
						uni.showModal({
							title: '获取验证码成功',
							content: '8888'
						})
					}
				}
				if (logOrResType === 'emailRegister') {
					let res = await this.$u.api.getRegisterCode({
						email: this.form.email
					})
					if(res.statusCode ===200){
						uni.showModal({
							title: '获取验证码成功',
							content: '8888'
						})
					}
				}
			},
			// 改变当前的表单内容
			changeType(idx) {
				switch (idx) {
					case 0:
						this.logOrResType = 'passwordLogin'
						break;
					case 1:
						this.logOrResType = 'codeLogin'
						break;
					case 2:
						this.logOrResType = 'phoneRegister'
						break;
					default:
						this.logOrResType = 'emailRegister'
				}
			},
			// 清除表单
			onCancel() {
				this.form = {
					login: '',
					name: '',
					phone: '',
					email: '',
					verifiable_code: '',
					password: '',
					repassword: ''
				}
			},
			
			
			// 登录成功后获取到用户携带的token
			async getUsersSuccessInfo(token){
				// 1.将token存储到本地,方便以后使用
				uni.setStorageSync('token', token)
				let { data } = await this.$u.api.getUser()			
				// 2. 拿到用户的信息存储到 vuex 中
				let userInfo = {
					name: this.form.login ? this.form.login : this.form.name,
					avater: this.form.avatar,
					liked: data.user.liked,
					commented: data.user.commented				
				}
				// 将当前的userInfo内容存储到vuex中去
				this.userLoginActions(userInfo)
				// 登录后,触发index页面的内容的重新请求
				uni.$emit('userIndexData')
				// 登录后,触发mine页面的内容的重新请求
				uni.$emit('meUserLogin')
			}
		}

	}
</script>

<style lang="scss" scoped>
	.login-box {
		display: flex;
		flex-wrap: wrap;
		justify-content: center;
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		padding: 40upx 20upx;
		background-color: #f1f1f1;
		border-radius: 30upx;

		.fork {
			position: absolute;
			top: 40upx;
			right: 20upx;

			image {
				width: 36upx;
				height: 36upx;
			}
		}

		.studyCenter {
			h4 {
				font-weight: 700;
				font-size: 36upx;
				text-align: center;
				color: #313234;
				padding: 10upx 0 30upx;
			}

			.btn {
				background-color: #0046f5;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 36upx;
				color: #fff;
				border-radius: 50upx;

				.wx {
					width: 36upx;
					height: 36upx;
					margin-right: 10upx;
				}
			}
		}

		.formArea {
			width: 85%;

			.btns {
				display: flex;
				justify-content: center;
				margin-top: 20upx;

				.submit {
					margin-right: 10upx;
				}
			}

			.login-register {
				margin-top: 30upx;
				display: flex;
				justify-content: center;

				text {
					padding: 0 8upx;
				}

				.textActive {
					background-color: #fff;
					color: #007cba;
				}
			}
		}

		.btnInfo {
			margin-top: 60upx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.webInfo {
				margin-top: 20upx;
				display: flex;
				color: #9eacd0;
			}
		}
	}
</style>
